package ltd.itlover.yqblog.login;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import javax.inject.Inject;

import cn.hutool.core.util.StrUtil;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import ltd.itlover.yqblog.R;
import ltd.itlover.yqblog.application.MyApplication;
import ltd.itlover.yqblog.dto.Result;
import ltd.itlover.yqblog.entity.User;
import ltd.itlover.yqblog.intent.IntentToRegister;
import ltd.itlover.yqblog.network.AccountApiService;
import ltd.itlover.yqblog.utils.TokenUtil;
import retrofit2.HttpException;
import retrofit2.Response;

@AndroidEntryPoint
public class LoginActivity extends AppCompatActivity {
    TextView textForToRegister;
    TextView textUsername;
    TextView textPassword;
    Button btnLogin;
    @Inject
    AccountApiService accountApiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();

    }

    private void init(){
        textForToRegister = (TextView) findViewById(R.id.text_to_register);
        btnLogin = (Button) findViewById(R.id.btn_login);
        textPassword = (TextView) findViewById(R.id.input_password);
        textUsername = (TextView) findViewById(R.id.input_username);

        textForToRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IntentToRegister.toRegisterPage();
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User user = checkForm();
                if(user != null){
                    requestLogin(user);
                }
                else{
                    makeInfo("请输入完整表单信息");
                }
            }
        });
    }

    private void requestLogin(User user){
        accountApiService.login(user)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Response<Result<String>>>() {
                    @Override
                    public void accept(Response<Result<String>> resultResponse) throws Exception {
                        //makeInfo("登录成功");
                        if(resultResponse.code() == 200){
                            makeInfo("登录成功");
                            String token = resultResponse.headers().get("Authorization");
                            TokenUtil.setToken(token);
                            requestMyInfoAndLoadToDatabase();
                        }
                        else{

                            String s = resultResponse.errorBody().string();
                            JSONObject jsonObject = new JSONObject(s);
                            makeInfo(jsonObject.getString("msg"));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        HttpException httpException = (HttpException) throwable;
                        String s = httpException.response().errorBody().string();
                        JSONObject jsonObject = new JSONObject(s);
                        makeInfo(jsonObject.getString("msg"));
                    }
                });
    }

    private void makeInfo(String msg){
        Toast.makeText(MyApplication.getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    private void requestMyInfoAndLoadToDatabase(){
        accountApiService.getInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<User>>() {
                    @Override
                    public void accept(Result<User> userResult) throws Exception {
                        User user = new User();
                         user = userResult.getData();
                        user.setToken(TokenUtil.getToken());
                        user.setUserId(user.getId());
                        user.save();
                        finish();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //makeInfo(TokenUtil.getToken());
//                        makeInfo(throwable.getMessage());
                        Log.i("错误", throwable.getMessage());
                    }
                });
    }

    private User checkForm(){
        String username = textUsername.getText().toString();
        String password = textPassword.getText().toString();

        if(StrUtil.hasBlank(username) || StrUtil.hasBlank(password)){
            return null;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return user;
    }
}